package net.cyl.interceptor;

import com.alibaba.cloud.commons.lang.StringUtils;
import feign.Request;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import net.cyl.emums.BizCodeEnum;
import net.cyl.model.LoginUser;
import net.cyl.util.CommonUtil;
import net.cyl.util.JWTUtil;
import net.cyl.util.JsonData;
import org.apache.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



@Slf4j

public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<LoginUser> loginUserThreadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(Request.HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())){
            response.setStatus(HttpStatus.SC_NO_CONTENT);
            return true;
        }

        String accsessToken = request.getHeader("token");
        log.info("accsessToken:{}",accsessToken);
        if(StringUtils.isBlank(accsessToken)){
            accsessToken = request.getParameter("token");
        }
        if(StringUtils.isNotBlank(accsessToken)){
          Claims claims = JWTUtil.parseToken(accsessToken);
          if(claims==null){
              CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
              return false;
          }

          long accountNo = (long) claims.get("accountNo");
          String headImg = (String) claims.get("headImg");
          String username = (String) claims.get("username");
          String phone = (String) claims.get("phone");
          String mail = (String) claims.get("mail");
          String auth = (String) claims.get("auth");

          LoginUser loginUser = LoginUser.builder()
                  .accountNo(accountNo)
                  .headImg(headImg)
                  .username(username)
                  .phone(phone)
                  .mail(mail)
                  .auth(auth)
                  .build();
          request.setAttribute("loginUser", loginUser);
          loginUserThreadLocal.set(loginUser);
          return true;

        }
        CommonUtil.sendJsonMessage(response, JsonData.buildResult(BizCodeEnum.ACCOUNT_UNLOGIN));
        return false;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
    }
    @Override
// 在请求完成之后执行的方法
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
    // TODO Auto-generated method stub
        loginUserThreadLocal.remove();
    }
}
